package com.priusoft.api.aop;

import com.priusoft.api.common.JwtUtil;
import com.priusoft.api.common.StringUtil;
import com.priusoft.api.domain.AjaxResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Aspect
public class TokenAspect {

    @Pointcut("@annotation(com.priusoft.api.aop.Token)")
    private void pointcut() {}

    @Around("pointcut()")
    public Object advice(ProceedingJoinPoint jp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String str = request.getHeader("token");
        if(StringUtil.isNotNullAndBlank(str)) {
            String username = JwtUtil.checkToken(str);
            if(StringUtil.isNotNullAndBlank(username)) {
                request.setAttribute("username",username);
                return jp.proceed();
            }
        }

        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(AjaxResult.error("没有权限").toString());
        return null;

    }

}
